<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p>
      This will use the userMedia audio and or video to get a stream. <br>
      It will then use mediaRecorder to "pipe" the data to StreamSaver (aka hard drive)
    </p>
    <p>
      Note: This is only allowed in
      <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/isSecureContext">secure web context</a>
    </p>

    <label><input id="$vid" type="checkbox"> Use Webcam</label>
    <label><input id="$aud" type="checkbox"> Use Microphone</label>
    <button id="$start">Start</button>
    <button id="$close">Close</button>

    <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/web-streams-polyfill@2.0.2/dist/ponyfill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/jimmywarting/browser-su@master/build/permissions.js"></script>
    <script src="../StreamSaver.js"></script>
    <script>
      $vid.disabled = $aud.disabled = $start.disabled = !window.isSecureContext
      $start.onclick = async () => {
        const permission = { name: 'userMedia', video: $vid.checked, audio: $aud.checked }
        const stream = await su.request(permission)
        const mediaRecorder = new MediaRecorder(stream)
        const ext = mediaRecorder.mimeType.split(';')[0].split('/')[1]
        const { readable, writable } = new TransformStream({
           transform: (chunk, ctrl) => chunk.arrayBuffer().then(b => ctrl.enqueue(new Uint8Array(b)))
        })
        const writer = writable.getWriter()
        readable.pipeTo(streamSaver.createWriteStream('media.' + ext))

        $close.onclick = event => {
          stopStream(stream)
          mediaRecorder.stop()
          setTimeout(() => {
            writer.close()
          }, 1000)
        }

        mediaRecorder.ondataavailable = evt => writer.write(evt.data)
        mediaRecorder.start()
      }

      function stopStream (stream) {
        let tracks = [
          ...stream.getAudioTracks(),
          ...stream.getVideoTracks()
        ]

        for (const track of tracks) track.stop()
      }
    </script>
  </body>
</html>
